import smtplib
from smtplib import SMTPDataError
from email.mime.text import MIMEText
from email.utils import formataddr
from datetime import datetime
from time import sleep
import os

my_sender = 'coco10069@qq.com'  # 发件人邮箱账号
my_pass = os.getenv(my_sender)
# my_sender = '3039991689@qq.com'
# my_pass = os.getenv(my_sender)
my_user = 'zj175@139.com'  # 收件人邮箱账号
interval = 30


def sendUnknownError(mName):
    msg = MIMEText('感知到%s于%s未连接' % (mName, datetime.now()), 'plain', 'utf-8')
    msg['From'] = formataddr(["未连接感知中枢", my_sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
    msg['To'] = formataddr(["Coco56", my_user])  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
    msg['Subject'] = "%s未连接，请处理" % mName  # 邮件的主题，也可以说是标题
    server = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 发件人邮箱中的SMTP服务器及端口
    server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
    server.sendmail(my_sender, [my_user, ], msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
    server.quit()  # 关闭连接
    sleep(interval)


def sendOfflineError(mName):
    msg = MIMEText('感知到%s于%s已掉线' % (mName, datetime.now()), 'plain', 'utf-8')
    msg['From'] = formataddr(["掉线感知中枢", my_sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
    msg['To'] = formataddr(["Coco56", my_user])  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
    msg['Subject'] = "%s已掉线，请处理" % mName  # 邮件的主题，也可以说是标题

    server = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 发件人邮箱中的SMTP服务器及端口
    server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
    try:
        server.sendmail(my_sender, [my_user, ], msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
    except SMTPDataError as e:
        print(e)
    server.quit()  # 关闭连接
    sleep(interval)


def sendAlarm(mName):
    msg = MIMEText('感知到%s于%s未正常工作' % (mName, datetime.now()), 'plain', 'utf-8')
    msg['From'] = formataddr(["异常感知中枢", my_sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
    msg['To'] = formataddr(["Coco56", my_user])  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
    msg['Subject'] = "%s未正常工作" % mName  # 邮件的主题，也可以说是标题

    server = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 发件人邮箱中的SMTP服务器及端口
    server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
    try:
        server.sendmail(my_sender, [my_user, ], msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
    except SMTPDataError as e:
        print(e)
    server.quit()  # 关闭连接


def sendRecoveredEmail(mName):
    msg = MIMEText('已于%s使用重启精灵方案修复%s' %(datetime.now(), mName), 'plain', 'utf-8')
    msg['From'] = formataddr(["集群修复中心", my_sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
    msg['To'] = formataddr(["Coco56", my_user])  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
    msg['Subject'] = "已完成对%s的修复" % mName  # 邮件的主题，也可以说是标题

    server = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 发件人邮箱中的SMTP服务器及端口
    server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
    try:
        server.sendmail(my_sender, [my_user, ], msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
    except SMTPDataError as e:
        print(e)
    server.quit()  # 关闭连接
    sleep(interval)


if __name__ == '__main__':
    sendAlarm('001')
